<template>
  <div class="box">
    <a-table
        :columns="columns"
        :dataSource="tableData"
        bordered
        :pagination="false"
        :loading="loading"
        :scroll="{
        x: 'max-content',
      }"
    >
      <template #title>
        <div style="text-align: right">
          <a-button type="primary" @click="addType">新增类型</a-button>
        </div>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key == 'sort'">
          {{ record.sort }}
        </template>
        <template v-if="column.key == 'status'">
          {{ record.source }}
        </template>
        <template v-if="column.key == 'desc'">
          {{ record.desc || "--" }}
        </template>
        <template v-if="column.key == 'action'">
          <a-button
              type="link"
              @click="editType(record)"
              :disabled="record.is_root == 1"
          >编辑
          </a-button
          >
          <a-button
              type="link"
              @click="showCompany"
              v-if="record.is_company==1"
          >渠道公司
          </a-button
          >
          <a-popconfirm
              title="确认删除该状态? "
              ok-text="确认"
              cancel-text="取消"
              @confirm="deleteType(record.id)"
          >
            <a-button type="link" v-if="record.is_root != 1" danger
            >删除
            </a-button
            >
          </a-popconfirm>
        </template>
      </template>
    </a-table>

    <!-- 新增、编辑状态 -->
    <a-drawer
        :title="title"
        :visible="showDrawer"
        :destroyOnClose="true"
        :width="$store.getters.isMobile ? '100%' : 450"
        :body-style="{
        height: 'calc(100% - 110px)',
        boxSizing: 'border-box',
        overflow: 'auto',
      }"
        @close="onClose"
    >
      <a-form layout="vertical">
        <a-row :wrap="true" :gutter="12">
          <a-col :span="24">
            <a-form-item label="状态名称" v-bind="validateInfos.source">
              <a-input
                  v-model:value="formData.source"
                  placeholder="请输入状态名称"
                  :maxlength="20"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="排序" v-bind="validateInfos.sort">
              <a-input-number
                  v-model:value="formData.sort"
                  :precision="0"
                  class="w-100p"
                  placeholder="请输入排序值"
                  :min="1"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="阶段描述" v-bind="validateInfos.desc">
              <a-textarea
                  placeholder="请输入阶段描述"
                  :auto-size="{ minRows: 3 }"
                  v-model:value="formData.desc"
                  :maxlength="200"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

      <div class="drawer-footer">
        <a-space>
          <a-button @click.prevent="onClose"> 取消</a-button>
          <a-button type="primary" @click.prevent="onSubmit"> 提交</a-button>
        </a-space>
      </div>
    </a-drawer>

    <!--  渠道公司  -->
    <ChannelCompany :visible="showCompanyDrawer" @toClose="showCompanyDrawer = false"/>
  </div>
</template>

<script>
import {watch, ref, toRefs, reactive} from "vue";
import request from "../../../../common/utils/request";
import {Form, message} from "ant-design-vue";
import ChannelCompany from "./ChannelCompany.vue";

const useForm = Form.useForm;

export default {
  props: {
    activeKey: {
      type: String,
      default: "",
    },
  },
  components: {
    ChannelCompany
  },
  setup(props, context) {
    const state = reactive({
      loading: false,
      title: "新增类型",
      editID: 0,
      showCompanyDrawer: false
    });
    const columns = [
      {
        title: "排序",
        key: "sort",
      },
      {
        title: "渠道状态",
        key: "status",
      },
      {
        title: "渠道描述",
        key: "desc",
      },
      {
        title: "操作",
        key: "action",
      },
    ];
    const tableData = ref([]);
    const getTableData = () => {
      state.loading = true;
      request
          .get("/org", "/business/customer/channel/sourceList")
          .then((res) => {
            console.log(res);
            tableData.value = res.list;
          })
          .finally(() => {
            state.loading = false;
          });
    };

    // 表单相关
    const formData = reactive({
      source: "",
      sort: 1, // 排序值
      desc: "",
    });
    const ruleRef = reactive({
      source: [{required: true, message: "必填"}],
      sort: [{required: true, message: "必填"}],
    });

    const {resetFields, validate, validateInfos} = useForm(formData, ruleRef);

    // 添加、编辑类型
    const showDrawer = ref(false);
    const addType = () => {
      state.editID = 0;
      state.title = "新增类型";
      showDrawer.value = true;
    };
    const editType = (val) => {
      state.editID = val.id;
      formData.source = val.source;
      formData.sort = val.sort;
      formData.desc = val.desc;
      state.title = "编辑类型";
      showDrawer.value = true;
    };
    // 删除
    const deleteType = (val) => {
      console.log(val);
      request
          .del("/org", "/business/customer/channel/delChannelType", {id: val})
          .then((res) => {
            message.success("删除成功！");
            getTableData();
          });
    };

    const refreshData = () => {
      showDrawer.value = false;
      resetFields();
      getTableData();
    };
    const onSubmit = () => {
      validate().then(() => {
        if (state.editID == 0) {
          // 新增
          const param = {
            ...formData,
          };
          request
              .post("/org", "/business/customer/channel/addChannelType", param)
              .then((res) => {
                console.log(res);
                message.success("添加成功！");
                refreshData();
              });
        } else {
          // 编辑
          const param = {
            ...formData,
            id: state.editID,
          };
          request
              .post("/org", "/business/customer/channel/editChannelType", param)
              .then((res) => {
                message.success("编辑成功！");
                refreshData();
              });
        }
      });
    };
    const onClose = () => {
      showDrawer.value = false;
    };

    const showCompany = () => {
      state.showCompanyDrawer = true
    }

    watch(
        () => props.activeKey,
        (val) => {
          if (val == "type") {
            getTableData();
          }
        },
        {
          immediate: true,
        }
    );

    return {
      ...toRefs(state),
      tableData,
      columns,
      showDrawer,
      addType,
      editType,
      deleteType,
      formData,
      ruleRef,
      validateInfos,
      onSubmit,
      onClose,
      showCompany
    };
  },
};
</script>

<style lang="less" scoped>
.box {
  padding: 10px;
}
</style>
